package com.example.dispatcher;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.example.xmlfactory.XMLFactory;
import com.example.xmlfactory.parse.Parser;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by huangbei on 2017/9/11.
 */

public class DispatchFactory {
    private Map<String,String> dispatchPath;
    private static DispatchFactory instance;
    private Parser parser;

    private DispatchFactory(){
        dispatchPath = new HashMap<>();
        parser = XMLFactory.getPullParser();
    }

    public static DispatchFactory getInstance(){
        if(instance == null){
            synchronized (DispatchFactory.class){
                if(instance == null){
                    instance = new DispatchFactory();
                }
            }
        }
        return instance;
    }

    public void init(InputStream inputStream){
        try {
            List<Jump> list = parser.parse(inputStream, Jump.class);
            for(Jump jump : list){
                this.dispatchPath.put(jump.getKey(), jump.getPath());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public void jump(Context context, String key){
        realJump(context,key,null,false,0);
    }

    public void jump(Context context,String key,Bundle bundle){
        realJump(context,key,bundle,false,0);
    }

    public void jumpForResult(Context context , String key , int requestCode){
        realJump(context,key,null,true,requestCode);
    }

    public void jumpForResult(Context context , String key , Bundle bundle , int requestCode){
        realJump(context,key,bundle,true,requestCode);
    }

    //真正跳转函数
    private void realJump(Context context , String key , Bundle bundle , boolean forResult , int requestCode){
        String path = dispatchPath.get(key);
        if(path == null){
            return;
        }
        try {
            Class obj = Class.forName(path);
            Intent intent = new Intent(context, obj);
            if(bundle != null){
                intent.putExtras(bundle);
            }
            if(forResult == false) {
                context.startActivity(intent);
            }else{
                ((Activity)context).startActivityForResult(intent,requestCode);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}
